package coordinator;

import java.util.Properties;
import org.omg.CORBA.ORB;
import org.omg.CosNaming.NamingContextExt;
import org.omg.CosNaming.NamingContextExtHelper;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAHelper;

import euclid.*;

/**
 * the main class for the coordinator
 *
 */
public class Coordinator {
	
	private static ORB orb;
	
	/**
	 * main class
	 * @param args what the client types in
	 */
	public static void main(String[] args) {
		//args[0] = host of orbd
		//args[1] = port of orbd
		//args[2] = name of the coordinator
		if(args.length != 3)
		{
			System.err.println("<orbd host> <orbd port> <name of the coordinator>");
			System.exit(-1);
		}
		try {
			Integer.parseInt(args[1]);//to check if the port is an int
			Properties props = new Properties();
			props.put("org.omg.CORBA.ORBInitialPort", args[1]);
			props.put("org.omg.CORBA.ORBInitialHost",args[0]);
			orb = ORB.init(args,props);
			System.out.println("ORB initialized.");
			
			//get the reference of rootPOA and activate POA Manager
			POA rootPoa =
					POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
			rootPoa.the_POAManager().activate();
			
			NamingContextExt nc = NamingContextExtHelper.narrow(
					orb.resolve_initial_references("NameService"));
			
			//Creation of the servant
			CoordinatorImpl coordinator = new CoordinatorImpl(args[2],rootPoa,nc);
			rootPoa.activate_object(coordinator);
			
			//get the object reference of Coordinator
			org.omg.CORBA.Object ref = rootPoa.servant_to_reference(coordinator);
			
			euclid.Coordinator coordRef = CoordinatorHelper.narrow(ref);
			
			// get the root naming context
	        org.omg.CORBA.Object objRef =
	        orb.resolve_initial_references("NameService");
	        //Use NamingContextExt instead of NamingContext. This is
	        // part of the Interoperable naming Service.
	        NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);
	        
	      //bind the reference of "coordRef" with the name chosen by the user (args[2])
			ncRef.rebind(ncRef.to_name(args[2]), coordRef);
		           
			System.out.println("Coordinator is ready and waiting for a request...");
			
			orb.run();
					
					
		}catch(NumberFormatException e){
			System.err.println("Please check the port");
		}catch(Exception e){
				System.err.println("Problem with the connexion. Please check the parameters.");
		}

	}

}
